package com.yyh.myblog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yyh
 * @date 2021/2/16
 * 异常处理
 * 其中@ControllerAdvice 拦截所有带有Controller的控制器
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    /**
     * 获取日志
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * ModelAndView exceptionHander()类 处理异常信息
     * ModelAndView对象：控制返回错误页面，添加后台输出到前端的一些信息
     * 类：exceptionHandler() 其中HttpSeverletRequest request输出访问的路径
     * 其中@ExceptionHandler()标识该方法可以做异常处理，Exception.class表示拦截的类为exception类
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
        //logger.error()"记录"异常信息和链接URL,其中request。getRequest()获取访问的URL
        logger.error("Request URL : {} , Exception : {}", request.getRequestURL(), e);
        //异常拦截判断，防止@ControllerAdvice拦截了所有异常
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        //创建对象
        ModelAndView mv = new ModelAndView();
        //将URL放入对象
        mv.addObject("url",request.getRequestURL());
        //获取异常信息
        mv.addObject("exception",e);
        //返回页面
        mv.setViewName("errors");
        return mv;
    }
}
